<template>
  <div class="wrapper">
    <div class="top" @click="goBack">
      <img src="@/assets/images/back_arrow.png" class="back" alt="header" />
    </div>
    <div class="main">
      <div class="header">
        <div class="header-title flex-center-center">
          <span class="title-text">选科对比</span>
          <span class="title-desc">选择科目，查看对比结果</span>
        </div>
      </div>
      <div class="form-wrapper shadow-wrapper">
        <div class="form-box">
          <div
            class="form-item flex-center-center pt0"
            @click="clickSelectProvince"
          >
            <div class="form-item-title">高考省份</div>
            <div class="form-item-content">
              <div
                :class="[
                  'form-item-content-item',
                  province == '选择省份' ? 'disabled' : '',
                ]"
              >
                {{ province }}
              </div>
              <img
                src="@/assets/images/icon_arrow_next.png"
                class="arrow"
                alt=""
              />
            </div>
          </div>
        </div>
      </div>
      <div class="subject-wrapper shadow-wrapper">
        <div class="subject-outer">
          <div class="subject-inner" v-if="province != '北京'">
            <div class="select flex-center-center">
              <span class="dot leftDot"></span>
              <span class="text">{{ leftSelectNames }}</span>
            </div>
            <div class="subject-box">
              <div class="subject-item flex-align-center">
                <div class="title">首选科目</div>
                <div class="value flex">
                  <div
                    :class="[
                      'value-item',
                      'long',
                      item.checked ? 'leftActive' : '',
                    ]"
                    v-for="item in leftMainSubjects"
                    :key="item.name"
                    @click="onClickMainItem(item, leftMainSubjects)"
                  >
                    {{ item.name }}
                  </div>
                </div>
              </div>
              <div class="subject-item flex-align-center">
                <div class="title">再选科目</div>
                <div class="value flex">
                  <div
                    :class="[
                      'value-item',
                      'short',
                      item.checked ? 'leftActive' : '',
                    ]"
                    v-for="item in leftMinorSubjects"
                    :key="item.name"
                    @click="onClickMinorItem(item, leftMinorSubjects)"
                  >
                    {{ item.name }}
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div class="subject-inner" v-else>
            <div class="select flex-center-center">
              <span class="dot leftDot"></span>
              <span class="text">{{ leftSelectNames }}</span>
            </div>
            <div class="subject-box">
              <div class="subject-item flex-align-center">
                <div class="title width-20">6选3科目</div>
                <div class="value flex-wrap width-450">
                  <div
                    :class="[
                      'value-item',
                      'short',
                      item.checked ? 'leftActive' : '',
                    ]"
                    v-for="item in leftSixSubjectList"
                    :key="item.name"
                    @click="onClickSixItem(item, leftSixSubjectList)"
                  >
                    {{ item.name }}
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div class="subject-inner" v-if="province != '北京'">
            <div class="select flex-center-center">
              <span class="dot rightDot"></span>
              <span class="text">{{ rightSelectNames }}</span>
            </div>
            <div class="subject-box">
              <div class="subject-item flex-align-center">
                <div class="title">首选科目</div>
                <div class="value flex">
                  <div
                    :class="[
                      'value-item',
                      'long',
                      item.checked ? 'rightActive' : '',
                    ]"
                    v-for="item in rightMainSubjects"
                    :key="item.name"
                    @click="onClickMainItem(item, rightMainSubjects)"
                  >
                    {{ item.name }}
                  </div>
                </div>
              </div>
              <div class="subject-item flex-align-center">
                <div class="title">再选科目</div>
                <div class="value flex">
                  <div
                    :class="[
                      'value-item',
                      'short',
                      item.checked ? 'rightActive' : '',
                    ]"
                    v-for="item in rightMinorSubjects"
                    :key="item.name"
                    @click="onClickMinorItem(item, rightMinorSubjects)"
                  >
                    {{ item.name }}
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div class="subject-inner" v-else>
            <div class="select flex-center-center">
              <span class="dot rightDot"></span>
              <span class="text">{{ rightSelectNames }}</span>
            </div>
            <div class="subject-box">
              <div class="subject-item flex-align-center">
                <div class="title">6选3科目</div>
                <div class="value flex-wrap width-450">
                  <div
                    :class="[
                      'value-item',
                      'short',
                      item.checked ? 'rightActive' : '',
                    ]"
                    v-for="item in rightSixSubjectList"
                    :key="item.name"
                    @click="onClickSixItem(item, rightSixSubjectList)"
                  >
                    {{ item.name }}
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="btn-box">
          <div :class="['btn']" @click="handleClickCompare">立即对比</div>
        </div>
      </div>
      <div class="tip">*参考2025高考招生情况</div>
    </div>

    <ProvincePopup
      v-if="isShowProvincePopup"
      :provinces="provinces"
      :selectProvinceObj="selectProvinceObj"
      @onProvinceSelect="onProvinceSelect"
      @onCloseProvince="onCloseProvince"
    >
    </ProvincePopup>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, reactive, watch } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { cloneDeep } from 'lodash-es';
import { useSubjectSelectStore } from '@/store/subjectSelect';
import { getVolunteerRegion, recodeAddOne } from '@/api/volunteer';
import {
  mainSubjectList,
  minorSubjectList,
  sixSubjectList,
} from '@/utils/subjectData';
import { onBackPressed } from '@/utils/androidFn.js';
import ProvincePopup from '@/components/ProvincePopup.vue';
import { showToast } from 'vant';

const route = useRoute();
const router = useRouter();
const store = useSubjectSelectStore();

const leftMainSubjects = ref(cloneDeep(mainSubjectList));
const rightMainSubjects = ref(cloneDeep(mainSubjectList));
const leftMinorSubjects = ref(cloneDeep(minorSubjectList));
const rightMinorSubjects = ref(cloneDeep(minorSubjectList));
const leftSixSubjectList = ref(cloneDeep(sixSubjectList));
const rightSixSubjectList = ref(cloneDeep(sixSubjectList));

const selectMainSubject = ref([]);
const onClickMainItem = (item, arr) => {
  arr.forEach((item) => {
    item.checked = false;
  });
  item.checked = !item.checked;
};

const selectMinorSubject = ref([]);
const onClickMinorItem = (item, arr) => {
  // 如果当前项未选中，且已经有2个选中项，则不允许再选
  const selectedItems = arr.filter((item) => item.checked);
  if (!item.checked && selectedItems.length >= 2) {
    showToast('最多只能选择2个科目');
    return;
  }

  // 切换当前项的选中状态
  item.checked = !item.checked;

  // 更新selectMinorSubject为当前所有选中的科目名称
  selectMinorSubject.value = arr
    .filter((item) => item.checked)
    .map((item) => item.name);
};

const onClickSixItem = (item, arr) => {
  // 如果当前项未选中，且已经有2个选中项，则不允许再选
  const selectedItems = arr.filter((item) => item.checked);
  if (!item.checked && selectedItems.length >= 3) {
    showToast('最多只能选择3个科目');
    return;
  }

  // 切换当前项的选中状态
  item.checked = !item.checked;

  // 更新selectMinorSubject为当前所有选中的科目名称
  selectMinorSubject.value = arr
    .filter((item) => item.checked)
    .map((item) => item.name);
};

const leftSelectNames = ref('请选择');
const rightSelectNames = ref('请选择');

const provinces = ref([]);
const getVolunteerRegionFn = async () => {
  const params = {
    platform: 4,
  };
  const res = await getVolunteerRegion(params);
  if (res.code == 200) {
    provinces.value = [];
    res.data.forEach((item) => {
      if (item.type != 2) {
        provinces.value.push({
          ...item,
          name: item.regionName,
          value: item.regionId,
          checked: false,
        });
      }
    });
    store.setProvinces(provinces.value);
  }
};
getVolunteerRegionFn();

const province = ref('选择省份');
const provinceId = ref('');
XMLDocument;
const isShowProvincePopup = ref(false);
const selectProvinceObj = ref({});

const onProvinceSelect = (item) => {
  isShowProvincePopup.value = false;
  selectProvinceObj.value = item;
  province.value = item.name;
};

const onCloseProvince = () => {
  isShowProvincePopup.value = false;
};

const clickSelectProvince = () => {
  isShowProvincePopup.value = true;
};

const leftSelectSubjectList = ref([]);
const rightSelectSubjectList = ref([]);
const handleClickCompare = () => {
  if (!selectProvinceObj.value.name) {
    showToast('请选择省份');
    return;
  }
  if (leftSelectSubjectList.value.length < 3) {
    showToast('左侧请选择三个科目');
    return;
  }
  if (rightSelectSubjectList.value.length < 3) {
    showToast('右侧请选择三个科目');
    return;
  }
  const storageData = {
    leftSelectSubjectList: leftSelectSubjectList.value,
    rightSelectSubjectList: rightSelectSubjectList.value,
    province: selectProvinceObj.value,
  };
  store.setCompareData(storageData);
  recodeAddOneFn(storageData);
  router.push({
    path: '/compareReport',
  });
};

const recodeAddOneFn = async (content) => {
  const params = {
    recordType: 20,
    searchContent: JSON.stringify(content),
  };
  const res = await recodeAddOne(params);
};

const goBack = () => {
  if (route.query?.fromType == 'android') {
    onBackPressed(router);
  } else {
    router.go(-1);
  }
};

const getCacheData = () => {
  selectProvinceObj.value = store.compareData.province;
  console.log('selectProvinceObj', selectProvinceObj);
  province.value = selectProvinceObj.value.name || '选择省份';
  const temp =
    store.compareData?.subjectList || store.compareData?.leftSelectSubjectList;
  console.log('temp', temp);
  if (temp.length) {
    temp.forEach((item) => {
      leftMainSubjects.value.forEach((_item) => {
        if (_item.name == item.name) {
          _item.checked = true;
        }
      });
      leftMinorSubjects.value.forEach((_item) => {
        if (_item.name == item.name) {
          _item.checked = true;
        }
      });
      leftSixSubjectList.value.forEach((_item) => {
        if (_item.name == item.name) {
          _item.checked = true;
        }
      });
    });
  }
  const tempRightData = store.compareData?.rightSelectSubjectList;
  if (tempRightData?.length) {
    tempRightData.forEach((item, index) => {
      rightMainSubjects.value.forEach((_item) => {
        if (_item.name == item.name) {
          _item.checked = true;
        }
      });
      rightMinorSubjects.value.forEach((_item) => {
        if (_item.name == item.name) {
          _item.checked = true;
        }
      });
      rightSixSubjectList.value.forEach((_item) => {
        if (_item.name == item.name) {
          _item.checked = true;
        }
      });
    });
  } else {
    rightSelectNames.value = '请选择';
  }
};

watch(
  [leftMainSubjects, leftMinorSubjects],
  ([newMain, newMinor]) => {
    const checkedMainName = newMain
      .filter((item) => item.checked)
      .map((item) => item.shortName);
    const checkedMain = newMain.filter((item) => item.checked);
    const checkedMinorName = newMinor
      .filter((item) => item.checked)
      .map((item) => item.shortName);
    const checkedMinor = newMinor.filter((item) => item.checked);
    leftSelectNames.value =
      [...checkedMainName, ...checkedMinorName].join('') || '请选择';
    leftSelectSubjectList.value = [...checkedMain, ...checkedMinor];
  },
  { deep: true }
);

watch(
  [rightMainSubjects, rightMinorSubjects],
  ([newMain, newMinor]) => {
    const checkedMainName = newMain
      .filter((item) => item.checked)
      .map((item) => item.shortName);
    const checkedMain = newMain.filter((item) => item.checked);
    const checkedMinorName = newMinor
      .filter((item) => item.checked)
      .map((item) => item.shortName);
    const checkedMinor = newMinor.filter((item) => item.checked);
    rightSelectNames.value =
      [...checkedMainName, ...checkedMinorName].join('') || '请选择';
    rightSelectSubjectList.value = [...checkedMain, ...checkedMinor];
  },
  { deep: true }
);

watch(
  () => [leftSixSubjectList],
  () => {
    leftSelectNames.value = leftSixSubjectList.value
      .filter((item) => item.checked)
      .map((item) => item.shortName)
      .join('');
    const checkedMain = leftSixSubjectList.value.filter((item) => item.checked);
    leftSelectSubjectList.value = checkedMain;
  },
  { deep: true }
);
watch(
  () => [rightSixSubjectList],
  () => {
    if (province.value == '北京') {
      rightSelectNames.value = rightSixSubjectList.value
        .filter((item) => item.checked)
        .map((item) => item.shortName)
        .join('');
      const checkedMain = rightSixSubjectList.value.filter(
        (item) => item.checked
      );
      rightSelectSubjectList.value = checkedMain;
    }
  },
  { deep: true }
);
watch(
  () => province.value,
  // 我想监听一下旧的值
  (newVal, oldVal) => {
    if (oldVal == '选择省份') {
      return;
    } else {
      console.log('进入Province监听器', newVal, oldVal);
      if (oldVal == '北京') {
        leftSelectNames.value = '请选择';
        rightSelectNames.value = '请选择';
        // leftMainSubjects中每一项的checked设置为false
        leftMainSubjects.value.forEach((item) => {
          item.checked = false;
        });
        leftMinorSubjects.value.forEach((item) => {
          item.checked = false;
        });
        rightMainSubjects.value.forEach((item) => {
          item.checked = false;
        });
        rightMinorSubjects.value.forEach((item) => {
          item.checked = false;
        });
      }
    }
  }
);
getCacheData();

onMounted(() => {});
</script>

<style scoped lang="scss">
.wrapper {
  width: 100%;
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: url('@/assets/images/homeBg.png') no-repeat center center;
  background-size: 100% 100%;
  .top {
    position: absolute;
    padding: 28px 30px 28px 30px;
    .back {
      width: 48px;
      height: 48px;
    }
  }
  .main {
    height: 100vh;
    padding: 0 60px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    .header {
      display: flex;
      justify-content: center;
      // margin-top: 136px;
      .robot-icon {
        width: 136px;
        height: 120px;
        margin-right: 18px;
      }
      .header-title {
        flex-direction: column;
        .title-text {
          font-weight: bold;
          font-size: 44px;
          color: #000000;
          margin-bottom: 12px;
          white-space: nowrap;
        }
        .title-desc {
          font-weight: 400;
          font-size: 22px;
          color: #555555;
          white-space: nowrap;
        }
      }
    }
    .shadow-wrapper {
      padding: 48px 32px;
      position: relative;
      border-radius: 16px;
      background-color: #f6fbfe;
      &::before {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        border-radius: 16px;
        padding: 2px;
        background: linear-gradient(
          180deg,
          rgba(255, 255, 255, 1),
          rgba(206, 231, 245, 1)
        );
        -webkit-mask: linear-gradient(#fff 0 0) content-box,
          linear-gradient(#fff 0 0);
        mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0);
        -webkit-mask-composite: xor;
        mask-composite: exclude;
        pointer-events: none;
      }
    }
    .form-wrapper {
      display: flex;
      justify-content: center;
      margin-top: 72px;
      .form-box {
        width: 40%;
        box-sizing: border-box;
        .form-item {
          position: relative;
          z-index: 1;
          justify-content: space-between;
          padding: 24px 0;
          border-bottom: 1px solid $border-color;
          &.pt0 {
            padding-top: 0;
          }
          .form-item-title {
            display: flex;
            align-items: center;
            font-size: 28px;
            color: $title-color;
            font-weight: bold;
          }
          .form-item-content {
            display: flex;
            align-items: center;
            font-size: 28px;
            color: $title-color;
            font-weight: bold;
            .form-item-content-item {
              padding: 0;
              margin-right: 12px;
              &.disabled {
                color: #999;
              }
            }
            .arrow {
              width: 32px;
              height: 32px;
            }
            :deep(.van-field) {
              background-color: #f6fbfe;
              .van-field__control {
                font-size: 28px;
                color: #000000;
              }
            }
          }
        }
      }
    }
    .subject-wrapper {
      margin-top: 16px;
      .subject-outer {
        display: flex;
        justify-content: center;
      }
      .subject-inner {
        &:first-child {
          padding-right: 74px;
          border-right: 2px solid #dde7f9;
        }
        &:last-child {
          padding-left: 74px;
        }
        .select {
          font-weight: bold;
          font-size: 32px;
          color: #333333;
          .dot {
            width: 18px;
            height: 18px;
            border-radius: 50%;
            margin-right: 12px;
            &.leftDot {
              background: #0b6eff;
            }
            &.rightDot {
              background: #41cf3e;
            }
          }
        }
        .subject-box {
          margin-top: 86px;
          .subject-item {
            &:first-child {
              padding-top: 0;
              border-bottom: 2px solid #dde7f9;
            }
            &:last-child {
              // padding-bottom: 0;
            }
            padding: 36px 0;
            .title {
              font-weight: bold;
              font-size: 28px;
              color: #333333;
              margin-right: 24px;
            }
            .width-450 {
              width: 450px;
            }
            .value {
              gap: 16px;
              .value-item {
                border-radius: 4px;
                background: #ffffff;
                border-radius: 4px;
                font-size: 28px;
                border: 2px solid #fff;
                &.long {
                  padding: 16px 100px;
                }
                &.short {
                  padding: 16px 32px;
                }
                &.leftActive {
                  border: 2px solid #0b6eff;
                  font-weight: bold;
                  font-size: 28px;
                  color: #0b6eff;
                  background: #e5edff;
                }
                &.rightActive {
                  border: 2px solid #41cf3e;
                  font-weight: bold;
                  font-size: 28px;
                  color: #168e13;
                  background-color: #e6ffe5;
                }
              }
            }
          }
        }
      }
    }
  }
  .btn-box {
    display: flex;
    justify-content: center;
    align-items: center;
    margin-top: 80px;
    .btn {
      width: 400px;
      text-align: center;
      background: $primary-color;
      border-radius: 12px;
      font-weight: bold;
      font-size: 24px;
      color: #ffffff;
      padding: 16px 0;
    }
  }
}
.tip {
  font-size: 22px;
  color: #888;
  margin-top: 24px;
  text-align: right;
}
</style>
